<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;

class User extends Controller
{
    private $sessionName = 'admin_user';

    public function index()
    {
        return 'admin it works !';
    }

    public function login()
    {
        if (Request::instance()->isPost()) {
            $username = input('post.username');
            if (empty($username)) {
                return $this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
            }
            $password = input('post.password');
            if (empty($password)) {
                return $this->error(lang('PASSWORD_REQUIRED'));
            }
            $verify = input('post.verify');
            if (empty($verify)) {
                return $this->error(lang('CAPTCHA_REQUIRED'));
            }
            if (!captcha_check($verify)) {
                return $this->error(lang('CAPTCHA_NOT_RIGHT'));
            };
            $userModel = new \app\admin\model\User();
            $user = $userModel->where(array('username' => $username))->find();
            if (empty($user)) {
                return $this->error(lang('USERNAME_NOT_EXIST'));
            }
            $inputPassword = get_md5_password($password, $user['salt']);
            if ($inputPassword . '###' != $user['password']) {
                return $this->error(lang('PASSWORD_NOT_RIGHT'));
            }
            Session::set($this->sessionName, json_encode($user));
            $data['last_login_ip'] = Request::instance()->ip();
            $data['last_login_time'] = date('Y-m-d H:is');
            $userModel->where(array('id' => $user['id']))->update($data);
            $this->redirect('Index/index');
        } else {
            $user = Session::get($this->sessionName);
            $user = json_decode($user, 1);
            if (!empty($user) && !empty($user['id'])) {
                $this->redirect('Index/index');
            }
            return $this->fetch('login');
        }
    }

    public function logout()
    {
        session($this->sessionName,null);
        $this->redirect('User/login');
    }

    public function password(){
        return $this->fetch();
    }
}
